package com.bo.startup;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import com.bo.WeiboConfig;
import com.bo.util.IOUtil;

public class AccessTokenFile {
	public static String searchAccessToken(String username){
		BufferedReader in = null;
		String currLine = null;
		try {
			InputStreamReader isr = new InputStreamReader(new FileInputStream(WeiboConfig.getValue("accessTokenFile").trim()), "UTF-8");   
			in = new BufferedReader(isr);
			while ((currLine = in.readLine()) != null) {
				if (currLine.trim().equals("")) {
					continue;
				}
				String []array=currLine.split("=");
				if(array[0].equals(username)){
					return array[1];
				}
			}	
		}catch(Exception io){
			io.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException ex) {				
			}
			in = null;
		}
		return null;
	}
	public static  void  writeAccessToken(String username,String accesstoken){
		try {
			String content=IOUtil.readFileToString(new File(WeiboConfig.getValue("accessTokenFile").trim()), "utf-8");
			String []rnarray=content.split("\r\n");
			StringBuffer sb=new StringBuffer();
			boolean bo=false;
			for(int i=0;i<rnarray.length;i++){
				String s=rnarray[i];
				int index=s.indexOf("=");
				if(index!=-1){
					String olduser=s.substring(0,index);
					if(olduser.equals(username)){
						sb.append(username);
						sb.append("=");
						sb.append(accesstoken);
						sb.append("\r\n");
						bo=true;
					}else{
						sb.append(s);
						sb.append("\r\n");
					}
				}
			}
			if(bo){
				IOUtil.writeStringToFile(new File(WeiboConfig.getValue("accessTokenFile").trim()), sb.toString(), "utf-8");
			}else{
				IOUtil.writeEndData(WeiboConfig.getValue("accessTokenFile").trim(), username+"="+accesstoken+"\r\n", "utf-8");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
//		AccessTokenFile at=new AccessTokenFile();
//		at.searchAccessToken();
	}
}
